<template>
  <view class="recharge-page">
    <!-- 顶部背景 -->
    <view class="recharge-header">
      <image class="header-bg" src="/static/Images/wallet/WalletToubu.png" mode="widthFix"></image>
      <view class="header-content">
        <view class="back-btn" @click="navigateBack">
          <image class="back-icon" src="/static/Images/wallet/Fanhuibai.png" mode="aspectFit"></image>
        </view>
        <view class="title">充值</view>
      </view>
    </view>
    
    <!-- 充值金额输入 -->
    <view class="recharge-card">
      <view class="recharge-amount-label">充值金额</view>
      <view class="recharge-amount-input">
        <text class="currency-symbol">¥</text>
        <input 
          class="amount-input" 
          type="digit" 
          v-model="customAmount" 
          placeholder="最小充值金额为¥10.00"
          @input="handleCustomAmountInput"
          @blur="handleAmountBlur"
        />
      </view>
      
      <!-- 快速选择金额 -->
      <view class="quick-amount-options">
        <view 
          v-for="(amount, index) in quickAmounts" 
          :key="index"
          class="quick-amount-item"
          :class="{active: customAmount === amount.toString()}"
          @click="selectQuickAmount(amount)"
        >
          {{ amount }}元
        </view>
      </view>
      
      <!-- 自定义金额输入框 -->
      <view class="custom-amount-container">
        <text class="custom-amount-label">充值金额</text>
        <input 
          class="custom-amount-input"
          type="number"
          placeholder="请输入金额"
          v-model="customAmount"
          @input="handleCustomAmountInput"
          @focus="onCustomAmountFocus"
          @blur="handleAmountBlur"
        />
      </view>
    </view>
    
    <!-- 支付方式选择 -->
    <view class="payment-method-card">
      <view class="card-title">支付方式</view>
      
      <!-- 微信支付选项 -->
      <view class="payment-option" @click="selectPaymentMethod('wechat')">
        <view class="payment-left">
          <view class="payment-info">
            <image class="payment-icon" src="/static/Images/wallet/WeiPay.png" mode="aspectFit"></image>
            <view class="payment-name">微信支付</view>
          </view>
        </view>
        <view class="payment-right">
          <view class="radio-button" :class="{active: paymentMethod === 'wechat'}"></view>
        </view>
      </view>
      
      <!-- 支付宝选项 -->
      <view class="payment-option" @click="selectPaymentMethod('alipay')">
        <view class="payment-left">
          <view class="payment-info">
            <image class="payment-icon" src="/static/Images/wallet/AliPay.png" mode="aspectFit"></image>
            <view class="payment-name">支付宝支付</view>
          </view>
        </view>
        <view class="payment-right">
          <view class="radio-button" :class="{active: paymentMethod === 'alipay'}"></view>
        </view>
      </view>
    </view>
    
    <!-- 提交按钮 -->
    <button class="confirm-btn" @click="confirmRecharge">确认充值</button>
    
    <!-- 底部指示器 -->
    <view class="bottom-indicator"></view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { userApi } from '@/utils/api';

// 支付方式
const paymentMethod = ref('alipay'); // 默认选择支付宝

// 快速选择金额选项
const quickAmounts = [10, 20, 30, 50, 100, 200];

// 自定义金额（作为主要的充值金额变量）
const customAmount = ref('');

// 选择快速金额
const selectQuickAmount = (amount) => {
  customAmount.value = amount.toString();
};

// 处理自定义金额输入
const handleCustomAmountInput = (e) => {
  const value = e.detail.value;
  // 限制只能输入数字和小数点
  if (value && !/^\d+(\.\d{0,2})?$/.test(value)) {
    return;
  }
  customAmount.value = value;
};

// 处理输入框失去焦点
const handleAmountBlur = () => {
  // 输入框失去焦点时不再自动创建订单
};

// 自定义金额输入框获得焦点
const onCustomAmountFocus = () => {
  // 输入框获得焦点时不需要特殊处理
};

// 选择支付方式
const selectPaymentMethod = (method) => {
  paymentMethod.value = method;
};

// 处理支付流程
const processPayment = async (orderId, amount) => {
  try {
    // 根据支付方式设置type和pay_type参数
    let type, pay_type;
    if (paymentMethod.value === 'wechat') {
      type = 1; // 微信支付
      // 判断是否为微信小程序环境
      // #ifdef MP-WEIXIN
      pay_type = 1; // 微信小程序
      // #endif
      // #ifndef MP-WEIXIN
      pay_type = 2; // 微信浏览器和H5
      // #endif
    } else if (paymentMethod.value === 'alipay') {
      type = 2; // 支付宝支付
      pay_type = undefined; // 支付宝不需要pay_type参数
    }
    
    // 调用充值支付接口
    const paymentParams = { recharge_id: orderId, type };
    if (pay_type !== undefined) {
      paymentParams.pay_type = pay_type;
    }
    
    const paymentResponse = await userApi.rechargePay(paymentParams);
    
    // 处理支付响应
    if (paymentResponse.code === 1) {
      // 支付宝支付
      if (paymentMethod.value === 'alipay') {
        handleAlipayPayment(paymentResponse.data);
      }
      // 微信支付
      else if (paymentMethod.value === 'wechat') {
        handleWechatPayment(paymentResponse.data, amount);
      }
    } else {
      uni.showToast({
        title: paymentResponse.msg || '支付失败，请重试',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.showToast({
      title: error.message || '支付失败，请重试',
      icon: 'none'
    });
  }
};

// 确认充值
const confirmRecharge = async () => {
  // 验证充值金额（使用自定义金额输入框的值）
  if (!customAmount.value) {
    uni.showToast({
      title: '请输入充值金额',
      icon: 'none'
    });
    return;
  }
  
  const amount = parseFloat(customAmount.value);
  
  // 验证最小充值金额
  if (amount < 10) {
    uni.showToast({
      title: '最小充值金额为¥10.00',
      icon: 'none'
    });
    return;
  }
  
  // 验证支付方式
  if (!paymentMethod.value) {
    uni.showToast({
      title: '请选择支付方式',
      icon: 'none'
    });
    return;
  }
  
  try {
    // 创建充值订单
    const response = await userApi.recharge({ money: amount });
    
    // 检查返回的code值
    if (response.code === 1) {
      // 订单创建成功，继续支付流程
      const orderId = response.data;
      await processPayment(orderId, amount);
    } else {
      // 订单创建失败
      uni.showToast({
        title: '充值失败，充值订单创建异常！',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.showToast({
      title: '充值失败，充值订单创建异常！',
      icon: 'none'
    });
  }
};

// 处理支付宝支付
const handleAlipayPayment = (formHtml) => {
  try {
    // #ifdef H5
    // H5环境下直接将表单插入页面并提交
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = formHtml;
    document.body.appendChild(tempDiv);
    
    // 查找并提交表单
    const form = tempDiv.querySelector('form');
    if (form) {
      form.submit();
    }
    
    // 清理临时元素
    setTimeout(() => {
      if (document.body.contains(tempDiv)) {
        document.body.removeChild(tempDiv);
      }
    }, 1000);
    // #endif
    
    // #ifdef MP-WEIXIN
    // 小程序环境下提示用户
    uni.showToast({
      title: '请在浏览器中完成支付',
      icon: 'none'
    });
    // #endif
    
  } catch (error) {
    console.error('支付宝支付处理失败:', error);
    uni.showToast({
      title: '支付处理失败，请重试',
      icon: 'none'
    });
  }
};

// 处理微信支付
const handleWechatPayment = (paymentData, amount) => {
  try {
    // 微信支付成功后的处理
    uni.showToast({
      title: '充值成功',
      icon: 'success',
      duration: 1500,
      success: () => {
        // 延迟跳转到充值成功页面
        setTimeout(() => {
          uni.navigateTo({
            url: `/pages/wallet/recharge-success?amount=${amount}`
          });
        }, 1500);
      }
    });
  } catch (error) {
    console.error('微信支付处理失败:', error);
    uni.showToast({
      title: '支付处理失败，请重试',
      icon: 'none'
    });
  }
};

// 返回上一页
const navigateBack = () => {
  uni.navigateBack();
};
</script>

<style lang="scss">
.recharge-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  position: relative;
}

/* 顶部背景 */
.recharge-header {
  position: relative;
  width: 100%;
  height: 130rpx;
}

.header-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.header-content {
  position: relative;
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 80rpx;
  position: relative;
}

.back-btn {
  position: absolute;
  left: 30rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

.title {
  color: #fff;
  font-size: 36rpx;
  font-weight: 500;
  text-align: center;
}

/* 充值金额卡片 */
.recharge-card {
  margin: 30rpx;
  padding: 30rpx;
  background-color: #fff;
  border-radius: 12rpx;
}

.recharge-amount-label {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 20rpx;
}

.recharge-amount-input {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  border-bottom: 1rpx solid #eee;
  padding-bottom: 20rpx;
  font-size: 20px;
}

.currency-symbol {
  font-size: 64rpx;
  font-weight: bold;
  color: #333;
  margin-right: 10rpx;
}

.amount-input {
  flex: 1;
  font-size: 1.2rem;
  font-weight: bold;
  color: #333;
  height: 80rpx;
}

/* 快速选择金额 */
.quick-amount-options {
  display: flex;
  flex-wrap: wrap;
  margin-top: 30rpx;
  gap: 10rpx;
  position: relative;
  z-index: 10;
}

.quick-amount-item {
  width: calc(33.33% - 7rpx);
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333;
  box-sizing: border-box;
  position: relative;
  z-index: 11;
}

/* 自定义金额容器 */
.custom-amount-container {
  width: 96%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 15rpx;
  padding: 20rpx;
  // background-color: #f8f9fa;
  border-radius: 8rpx;
  // border: 1rpx solid #e9ecef;
  z-index: 10;
  position: relative;
}

.custom-amount-label {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.custom-amount-input {
  flex: 1;
  margin-left: 20rpx;
  height: 60rpx;
  padding: 0 20rpx;
  background-color: #fff;
  border: 1rpx solid #ddd;
  border-radius: 6rpx;
  font-size: 28rpx;
  color: #333;
  text-align: left;
}

.quick-amount-item.active {
  background-color: #fff0f0;
  color: #ff4d4f;
  border: 1rpx solid #ff4d4f;
}

/* 支付方式卡片 */
.payment-method-card {
  margin: 0 30rpx 30rpx;
  padding: 30rpx;
  background-color: #fff;
  border-radius: 12rpx;
}

.card-title {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 30rpx;
}

.payment-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
}

.payment-left {
  display: flex;
  flex-direction: column;
}

.payment-info {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.payment-icon {
  width: 60rpx;
  height: 60rpx;
  margin-right: 20rpx;
}

.payment-name {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 6rpx;
}

.payment-right {
  display: flex;
  align-items: center;
}

.radio-button {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  border: 2rpx solid #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
}

.radio-button.active {
  border-color: #ff4d4f;
  background-color: #fff;
  position: relative;
}

.radio-button.active::after {
  content: '';
  width: 24rpx;
  height: 24rpx;
  border-radius: 50%;
  background-color: #ff4d4f;
  position: absolute;
}

/* 确认按钮 */
.confirm-btn {
  width: calc(100% - 60rpx);
  height: 90rpx;
  line-height: 90rpx;
  background-color: #ff4d4f;
  color: #fff;
  font-size: 32rpx;
  border-radius: 45rpx;
  margin: 40rpx auto;
  border: none;
}

/* 底部指示器 */
.bottom-indicator {
  width: 120rpx;
  height: 8rpx;
  background-color: #ddd;
  border-radius: 4rpx;
  margin: 30rpx auto;
}
</style>